import {
  Button,
  Card,
  ColorPicker,
  Form,
  Grid,
  Input,
  Link,
  Space,
} from "@arco-design/web-react";
import "./index.scss";
import { useAppSelector } from "@/store/hooks";
import { useDispatch } from "react-redux";
import {
  ThemeModel,
  setTheme,
  updateThemeList,
} from "@/store/modules/appSlice";
import CustomModal from "@/components/CustomModal";
import { useState } from "react";
import IconFont from "@/components/IconFont";
import {
  generateColorPalette,
  getColorGradient,
  getRandomHexColor,
} from "@/utils";
import { IconPlus } from "@arco-design/web-react/icon";
import useTheme from "@/hooks/useTheme";
import colorGenerator from "@/utils/colorGenerator";

const Row = Grid.Row;
const Col = Grid.Col;
const FormItem = Form.Item;

export default function Theme() {
  const [visible, setVisible] = useState(false);
  /** 添加主题的模板 */
  const addTemplate = {
    hex: "",
    chartColorList: [],
    key: "",
    title: "",
    colorList: [],
    preset: false,
  };

  const currentTheme = useAppSelector((state) => state.app.theme);
  const colorList = useAppSelector((state) => state.app.themeList);
  const dispatch = useDispatch();
  const [form] = Form.useForm();
  const [editTheme, seteditTheme] = useState<ThemeModel | null>();
  const [editThemeIndex, seteditThemeIndex] = useState<number>(0);

  /** -----编辑主题----- */
  const onUpdateTheme = (theme: ThemeModel, index: number) => {
    setVisible(true);
    seteditTheme({ ...theme });
    form?.setFieldsValue(theme);
    seteditThemeIndex(index);
  };
  const onSubmitUpdateTheme = (data: ThemeModel) => {
    const newdata = { ...editTheme, ...data };
    if (!newdata.preset) {
      //重新生成色板
      newdata.colorList = getColorGradient(newdata.hex, "rgb");
      newdata.rgb = useTheme.getColor(tinycolor(newdata.hex).toRgbString());
    }
    dispatch(
      updateThemeList({
        index: editThemeIndex,
        data: newdata,
        type: "update",
      })
    );
    dispatch(setTheme(newdata));
    setVisible(false);
  };

  /** -----添加主题----- */
  const onAddTheme = () => {
    const hex = getRandomHexColor()[0];
    const addData = {
      ...addTemplate,
      hex,
      chartColorList: colorGenerator.getAnalogousColors(hex, 4),
    };
    setVisible(true);
    form.setFieldsValue(addData);
    seteditTheme(addData);
  };
  const onSubmitAddTheme = (data: ThemeModel) => {
    dispatch(
      updateThemeList({
        index: -1,
        data,
      })
    );
  };

  /** -----删除主题----- */
  const onDeleteTheme = (data: ThemeModel, index: number) => {
    dispatch(
      updateThemeList({
        index: index,
        data,
        type: "delete",
      })
    );
  };

  /** 添加图表主题色 */
  const onAddColor = () => {
    const newTheme = { ...editTheme! };
    const chartColorList = [...newTheme.chartColorList];
    console.log(newTheme);
    // 随机生成一个相近色
    chartColorList.push(colorGenerator.getAnalogousColors(newTheme.hex)[0]);
    newTheme.chartColorList = chartColorList;
    form.setFieldValue("chartColorList", chartColorList);
    seteditTheme(newTheme);
  };

  const onDelColor = (index: number) => {
    const newTheme = { ...editTheme! };
    const chartColorList = [...editTheme!.chartColorList];
    chartColorList.splice(index, 1);
    form.setFieldValue("chartColorList", chartColorList);
    newTheme.chartColorList = chartColorList;
    seteditTheme(newTheme);
  };
  /** -----表单提交----- */
  const onSubmitForm = async () => {
    await form.validate();
    if (editTheme?.key) {
      form.submit();
    } else {
      const colors = generateColorPalette(form.getFieldValue("hex"));
      const formData = form.getFieldsValue() as ThemeModel;
      const data: ThemeModel = {
        ...formData,
        colorList: colors,
        rgb: useTheme.getColor(tinycolor(formData.hex).toRgbString()),
      };
      onSubmitAddTheme(data);
      setVisible(false);
    }
  };

  const onCancel = () => {
    const initValues: any = { ...addTemplate };
    seteditTheme(initValues);
    form.setFieldsValue(initValues);
  };

  return (
    <div className="w-full h-full overflow-y-auto">
      <Row className="w-full" gutter={[10, 10]}>
        {colorList.map((theme, index) => (
          <Col key={theme.title} xs={12} md={8} xl={6} lg={6} xxl={4}>
            <Card>
              <div className="h-60 flex flex-col">
                <div className="w-full flex-1  rounded-md overflow-hidden  text-white flex-center">
                  <div
                    className="flex-1 flex  justify-center items-center h-full"
                    style={{
                      background: theme.hex,
                      textShadow: "0 0 5px rgba(0,0,0,0.5)",
                    }}
                  >
                    {theme.title}
                  </div>
                  <div className="flex-1 h-full flex flex-col">
                    {theme.chartColorList?.map((color) => (
                      <div
                        key={color}
                        className="flex-1"
                        style={{ background: color }}
                      ></div>
                    ))}
                  </div>
                </div>

                <div className="text-center mt-4">
                  <Space>
                    <Button
                      disabled={theme.key === currentTheme?.key}
                      type="primary"
                      onClick={() => dispatch(setTheme(theme))}
                    >
                      {theme.key === currentTheme?.key ? "已应用" : "应用"}
                    </Button>

                    <Button onClick={() => onUpdateTheme(theme, index)}>
                      编辑
                    </Button>

                    {!theme.preset && (
                      <Button
                        status="danger"
                        onClick={() => onDeleteTheme(theme, index)}
                      >
                        删除
                      </Button>
                    )}
                  </Space>
                </div>
              </div>
            </Card>
          </Col>
        ))}

        <Col xs={12} md={8} xl={6} lg={6} xxl={4}>
          <Card>
            <div className="w-full h-60 flex-center">
              <span
                className="cursor-pointer hover:text-black"
                onClick={onAddTheme}
              >
                <IconPlus style={{ fontSize: 60 }} />
              </span>
            </div>
          </Card>
        </Col>

        <CustomModal
          onVisibleChange={(visible) => setVisible(visible)}
          visible={visible}
          title={`${editTheme?.key ? "编辑" : "添加"}主题`}
          width="700px"
          onOK={onSubmitForm}
          onCancel={onCancel}
        >
          <div>
            <Form
              onSubmit={onSubmitUpdateTheme}
              autoComplete="off"
              form={form}
              validateMessages={{
                required: (_, { label }) => `必须填写 ${label}`,
                string: {
                  length: `字符数必须是 #{length}`,
                  match: `不匹配正则 #{pattern}`,
                },
                number: {
                  min: `最小值为 #{min}`,
                  max: `最大值为 #{max}`,
                },
              }}
            >
              <FormItem
                rules={[{ required: true }]}
                field="title"
                label="主题名称"
              >
                <Input disabled={editTheme?.preset} placeholder="请输入" />
              </FormItem>
              <FormItem
                rules={[{ required: true }]}
                field="key"
                label="主题变量"
              >
                <Input disabled={editTheme?.preset} placeholder="全局唯一" />
              </FormItem>
              <FormItem rules={[{ required: true }]} field="hex" label="主题色">
                <ColorPicker
                  showPreset
                  disabled={editTheme?.preset}
                  showText
                  defaultValue="#ffffff"
                />
              </FormItem>
              <FormItem label="图表色板" shouldUpdate>
                {(values: ThemeModel) => {
                  return (
                    <Row>
                      {values?.chartColorList?.map((__color, index) => (
                        <Col className="flex " span={6} key={index}>
                          <FormItem field={`chartColorList[${index}]`}>
                            <ColorPicker key={index} showText showPreset />
                          </FormItem>
                          <div className="flex-shrink-0 ">
                            <Link
                              onClick={() => onDelColor(index)}
                              status="error"
                            >
                              删除
                            </Link>
                          </div>
                        </Col>
                      ))}
                      <Col span={6}>
                        <span
                          onClick={onAddColor}
                          className="text-3xl text-gray-400 cursor-pointer hover:text-gray-800"
                        >
                          <IconFont type="icon-tianjia1"></IconFont>
                        </span>
                      </Col>
                    </Row>
                  );
                }}
              </FormItem>
            </Form>
          </div>
        </CustomModal>
      </Row>
    </div>
  );
}
